#ifndef MY_INC_PHY_PHY_SignalAnalysisr_H_
#define MY_INC_PHY_PHY_SignalAnalysisr_H_

#include <MY_INC/PHY/PHY_math.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
// 系统参数
#define SAMPLE_RATE 50000.0f // 50kHz采样率
#define MIN_FREQ    49.5f    // 最小信号频率(Hz)
#define MAX_FREQ    50.5f    // 最大信号频率(Hz)
#define BUFFER_SIZE 512     // 环形缓冲区大小(2的幂次)

/**
 * @brief 定义正弦波分析器的结构体。
 */

// 移相器结构体
typedef struct
{
    // 移相专用

    float    buffer[BUFFER_SIZE]; // 采样数据环形缓冲区
    uint16_t write_index;         // 缓冲区写指针
    float    delay_samples;       // 当前延迟点数(动态计算)
    float    phaseshifter_output; // 输出：移相后的信号
    float    phaseshifter_angle;  // 移相角,单位：度(0-360°)

    // RMS专用
    float Vrms; // 输出：信号的均方根值（RMS，Vrms）
    float Vacc_rms;
    // 通用检测变量
    uint16_t nsamplesMin; // 样本数最小限制（用于过滤异常值，nsamplesMin）
    uint16_t nsamplesMax; // 样本数最大限制（用于过滤异常值，nsamplesMax）
    float    curr_sample_norm;
    bool     prev_sign;
    bool     curr_sign;
    uint16_t nsamples;
    float    inv_nsamples;
    uint16_t buffer_size;
    float    SigFreq;
    float    SampleFreq;
    float    Threshold; // 过零检测阈值
} SignalAnalysisr_Typedef;
typedef struct
{
    SignalAnalysisr_Typedef Phase[3];
} ThreePhaseSignalAnalysisr_Typedef;
void SignalAnalysisr_Init(SignalAnalysisr_Typedef *v, float SampleFreq, float Threshold, uint32_t nsamplesMin,
                          uint32_t nsamplesMax);
void SignalAnalysisr_Reset(SignalAnalysisr_Typedef *v);

void ThreePhaseSignalAnalysisr_Init(ThreePhaseSignalAnalysisr_Typedef *v, float SampleFreq, float Threshold,
                                    uint32_t nsamplesMin, uint32_t nsamplesMax);

static inline void  ThreePhaseSineAnalyzer_ProcessSample_Inline(ThreePhaseSignalAnalysisr_Typedef *v, float Ac_Input[3],
                                                                float phase_deg); // 处理三相正弦波样本
static inline void  SignalAnalysisr_ProcessSample_Inline(SignalAnalysisr_Typedef *v, float adc_sample); // 初始化移相器
static inline float SignalAnalysisr_PSGetOutput_Inline(SignalAnalysisr_Typedef *ps); // 获取移相后的输出
static inline void  SignalAnalysisr_ProcessSample_Inline(SignalAnalysisr_Typedef *v, float adc_sample)
{
    if (v->phaseshifter_angle > 360.0f)
        v->phaseshifter_angle -= 360.0f; // 确保角度在0-360度范围内
    if (v->phaseshifter_angle < 0.0f)
        v->phaseshifter_angle += 360.0f; // 确保角度在0-360度范围内
    v->curr_sign = (bool)(adc_sample > v->Threshold);
    v->nsamples++;
    v->Vacc_rms += (adc_sample * adc_sample) - (v->buffer[v->write_index] * v->buffer[v->write_index]);
    v->buffer[v->write_index] = adc_sample;                   // 存储新样本到环形缓冲区
    v->write_index = (v->write_index + 1) % (v->buffer_size); // 更新写指针(环形缓冲区)
    if ((!v->prev_sign) & (v->curr_sign))
    {
    	float SigFreq = 50.0f;
        if (((v->nsamplesMin < v->nsamples) & (v->nsamples < v->nsamplesMax)))
        {
            v->inv_nsamples = (1.0f) / (v->nsamples);
            v->buffer_size = v->nsamples;
            v->delay_samples = ((v->phaseshifter_angle) * (0.00277777777777f) *
                                (float)(v->nsamples));      // 动态计算延迟点数: delay = (θ/2π) * (fs/f)
            SigFreq = (v->SampleFreq * v->inv_nsamples); // 计算信号频率（SigFreq）
        }
        else
        {
            v->inv_nsamples = (1.0f) / ((float)SAMPLE_RATE / 50.0f);
            v->buffer_size = BUFFER_SIZE;
        }

        v->SigFreq = 0.01f * SigFreq + 0.99f * v->SigFreq;
        v->nsamples = 0; // 清空样本数
        v->write_index = 0;
    }
    v->prev_sign = v->curr_sign;                                                  // 更新上一个符号
    v->Vrms = sqrtf(v->Vacc_rms * v->inv_nsamples) * 0.0001f + 0.9999f * v->Vrms; // d返回 RMS 值
    if(isnan(v->Vrms))
    {
    	v->Vrms = v->Vacc_rms = 0.0f;
    }
    int16_t read_pos = (v->write_index - (int16_t)v->delay_samples) - 1;          // 补偿延迟
    // 处理负索引
    while (read_pos < 0)
        read_pos += v->buffer_size;
    v->phaseshifter_output = v->buffer[read_pos];
}

// phase_deg输入正数0-180，获得滞后于原信号的相位，180-360反之超前[180-0]°
static inline float SignalAnalysisr_PSGetOutput_Inline(SignalAnalysisr_Typedef *v)
{
    // 计算需要读取的位置(带小数部分)
    int16_t read_pos = (v->write_index - (int16_t)v->delay_samples) - 1; // 补偿延迟
    // 处理负索引
    while (read_pos < 0)
        read_pos += v->buffer_size;
    v->phaseshifter_output = v->buffer[read_pos];
    return v->phaseshifter_output;
}
static inline void ThreePhaseSineAnalyzer_ProcessSample_Inline(ThreePhaseSignalAnalysisr_Typedef *v, float Ac_Input[3],
                                                               float phase_deg)
{
    v->Phase[0].phaseshifter_angle = phase_deg;
    v->Phase[1].phaseshifter_angle = phase_deg;
    v->Phase[2].phaseshifter_angle = phase_deg;
    SignalAnalysisr_ProcessSample_Inline(&v->Phase[0], Ac_Input[0]);
    SignalAnalysisr_ProcessSample_Inline(&v->Phase[1], Ac_Input[1]);
    SignalAnalysisr_ProcessSample_Inline(&v->Phase[2], Ac_Input[2]);
}
#endif /* Parameter_H_ */
